package com.xixudi.htmlto;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @desc 使用wkhtmltopdf 把html转为pdf
 * @author YangZheng 328170112@qq.com
 * @date 2019-02-21 19:49
 */
public class MakePDF {
    public static String pdfPath = JfinalDoc.class.getClassLoader().getResource("pdf").getPath().substring(1);

    public static void htmlToPdf(String htmlPath, String newPdfPath) {
        String opts = "--outline --outline-depth 2" +//生成目录,深度2
                " --margin-top 5mm --margin-right 5mm --margin-bottom 5mm --margin-left 5mm";//边距
        String command = "\"" + pdfPath + "/wkhtmltopdf.exe\" " + opts + " \"" + htmlPath + "\" \"" + newPdfPath + "\"";
        System.out.println(command);
        BufferedReader reader = null;
        try {
            Process p = Runtime.getRuntime().exec(command);
            String s = null;
            reader = new BufferedReader(new InputStreamReader(p.getErrorStream(), "gbk"));
            while ((s = reader.readLine()) != null) {
                System.err.println(s);
            }
            p.waitFor();
            System.out.println("end!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}